package com.followme.module.common;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

public class ExportDbActivity extends Activity implements OnClickListener {

	private static final String SAMPLE_DB_NAME = "FollowMeDataBase";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.button1).setOnClickListener(this);
        findViewById(R.id.button2).setOnClickListener(this);
    }

	@Override
	public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.button1) {
            deleteDB();

        } else if (i == R.id.button2) {
            exportDB();

        }
	}

	private void deleteDB(){
		boolean result = this.deleteDatabase(SAMPLE_DB_NAME);
		if (result==true) {
			 Toast.makeText(this, "DB Deleted!", Toast.LENGTH_LONG).show();
		}
	}

	private void exportDB(){
		File sd = Environment.getExternalStorageDirectory();
        File data = Environment.getDataDirectory();
        FileChannel source=null;
        FileChannel destination=null;
        String currentDBPath = "/data/"+ "com.tracking.application" +"/databases/"+SAMPLE_DB_NAME;
        String backupDBPath = SAMPLE_DB_NAME;
        File currentDB = new File(data, currentDBPath);
        File backupDB = new File(sd, backupDBPath);
        try {
            source = new FileInputStream(currentDB).getChannel();
            destination = new FileOutputStream(backupDB).getChannel();
            destination.transferFrom(source, 0, source.size());
            source.close();
            destination.close();
            Toast.makeText(this, "DB Exported!", Toast.LENGTH_LONG).show();
        } catch(IOException e) {
        	e.printStackTrace();
        }
	}
}
